<template>
  <div class="page-container">
    <el-container>
      <el-aside width="200px" class="page-aside" v-drag v-collapse>
        <cm-organization-tree ref="organizationTree" @handleNodeClick="handleNodeClick" />
      </el-aside>
      <el-main class="page-main">
        <!--表格内容栏-->
        <cm-table
          ref="dataTable"
          pkName="id"
          :filters="filters"
          :filterFields="filterFields"
          :columns="columns"
          :checkRowOpShow="checkRowOpShow"
          @handleAjaxSuccess="handleAjaxSuccess"
          @handleTableOperator="handleTableOperator"
          @handleCellOperator="handleCellOperator"
        ></cm-table>
      </el-main>
    </el-container>

    <!--新增编辑界面-->
    <el-dialog
      :title="operator"
      width="65%"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <el-form
        :model="formData"
        label-width="120px"
        :disabled="!dialogEdit"
        :hide-required-asterisk="!dialogEdit"
        :rules="rules"
        ref="dataForm"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="简称" prop="shortName">
              <el-input v-model="formData.shortName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="全称" prop="fullName">
              <el-input v-model="formData.fullName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="科长" prop="chiefId">
              <cm-employee v-model="formData.chiefId"></cm-employee>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分管领导" prop="leadId">
              <cm-employee v-model="formData.leadId"></cm-employee>
            </el-form-item>
          </el-col>
        </el-row>
        <!--
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input v-model="formData.address"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactMan">
              <el-input v-model="formData.contactMan"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model="formData.contactPhone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <cm-select v-model="formData.type" dicCode="dicOrgType"></cm-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="ordinal">
              <el-input v-model.number="formData.ordinal" :min="1"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否有效" prop="valid">
              <cm-radio v-model="formData.valid" dicCode="dicYesNo"></cm-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" :rows="5" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-input v-model="formData.createTime" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button
          v-if="dialogEdit"
          size="large"
          type="info"
          @click="dialogVisible=false"
        >取消</el-button>
        <el-button
          v-if="dialogEdit"
          size="large"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >提交</el-button>
        <el-button
          v-if="!dialogEdit"
          size="large"
          type="info"
          @click="dialogVisible=false"
        >关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, nextTick} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import api from '@/http/api';
import {useOrganizationStore} from '@/pinia/modules/organization';

const organizationStore = useOrganizationStore();
const filters = ref({
  fullName: '',
  type: '',
  parentId: ''
});
const filterFields = ref([
  {prop: "fullName", label: "简称"},
  {prop: "type", label: "类型", type: 'select', dicCode: 'dicOrgType'},
]);
const columns = ref([
  {prop: "shortName", label: "简称", minWidth: 160, click: true},
  {prop: "fullName", label: "全称", minWidth: 160},
  {prop: "chiefName", label: "科长", minWidth: 120},
  {prop: "leadName", label: "分管领导", minWidth: 120},
  {prop: "ordinal", label: "排序", minWidth: 80, type: 'number'},
  {prop: "type", label: "类型", minWidth: 80, type: 'select', dicCode: 'dicOrgType'},
  //{prop: "contactMan", label: "联系人", minWidth: 110},
  //{prop: "contactPhone", label: "联系方式", minWidth: 110},
  {prop: "valid", label: "是否有效", minWidth: 110, type: 'radio', dicCode: 'dicYesNo'},
  {prop: "remark", label: "备注", minWidth: 120},
  {prop: "createTime", label: "创建时间", minWidth: 160}
]);
const operator = ref('');
const dialogVisible = ref(false);
const dialogEdit = ref(true);
const editLoading = ref(false);
const formData = ref({valid: ''});
const rules = ref({
  shortName: [{required: true, message: '请输入简称', trigger: 'blur'}],
    fullName: [{required: true, message: '请输入全称', trigger: 'blur'}],
    type: [{required: true, message: '请选择类型', trigger: 'change'}],
    valid: [{required: true, message: '请选择是否有效', trigger: 'change'}],
    ordinal: [
    {required: true, message: '请输入排序', trigger: 'blur'},
    {type: 'number', message: '排序必须为数字', trigger: 'blur'}
  ]
});
const organizationTree = ref();
const dataTable = ref();
const dataForm = ref();

const handleNodeClick = (data) => {
  filters.value.parentId = data.id;
  dataTable.value.findPage();
};

const checkRowOpShow = (op, row) => {
  return !(op.name
    && ((op.name.indexOf('有效') >= 0 && row.valid === '1')
      || (op.name.indexOf('无效') >= 0 && row.valid === '0')));
};

// 单元格操作
const handleCellOperator = (property, value, row) => {
  formData.value = Object.assign({}, row);
  dialogVisible.value = true;
  dialogEdit.value = false;
  operator.value = "查看";

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const handleTableOperator = (button, row) => {
  if (button.buttonType === 'edit') {
    formData.value = Object.assign({}, row, {button: button})
  } else if(button.buttonType === 'add') {
    if (filters.value.parentId === '') {
      ElMessage.warning('请先在左侧组织机构中选择要添加部门的单位！');
      return;
    }
    formData.value = {parentId: filters.value.parentId, button: button, valid: '1'};
  } else {
    formData.value = {parentId: filters.value.parentId, button: button, valid: '1'};
  }

  dialogVisible.value = true;
  dialogEdit.value = true;
  operator.value = button.name;
  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

// 删除成功回调
const handleAjaxSuccess = () => {
  reloadTreeData();
};

const reloadTreeData = async(id) => {
  await organizationStore.reloadOrganization()
  await organizationTree.value.loadOrganization(id);
};

// 保存
const submitForm = () => {
  dataForm.value.validate((valid) => {
    if (valid) {
      if (formData.value.type !== '03') {
        formData.value.isWarehouse = '';
      }
      if (formData.value.type !== '04' && formData.value.type !== '05' && formData.value.type !== '09') {
        formData.value.isProduct = '';
      }
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true
        api.post(formData.value.button.dataDestUrl, formData.value).then(res => {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          dataForm.value && dataForm.value.clearValidate();
          dataTable.value.findPage();
          reloadTreeData(res.data.id);
          editLoading.value = false;
        }).catch(() => {
          editLoading.value = false;
        });
      }).catch(()=>{});
    }
  });
};
</script>

<style scoped>
.tree-row :deep(.el-tree--highlight-current .el-tree-node.is-currentnst .el-tree-node__content) {
  background-color: #C7E1FF
}
</style>
